package com.jstyle.jclife.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.ExerciseMode;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.HealthHistoryActivity;
import com.jstyle.jclife.activity.HeartHistoryActivity;
import com.jstyle.jclife.activity.HeartTipsActivity;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.UserInfoDaoManager;
import com.jstyle.jclife.model.HeartData;
import com.jstyle.jclife.model.UserInfo;
import com.jstyle.jclife.utils.ChartDataUtil;
import com.jstyle.jclife.utils.DateUtil;
import com.jstyle.jclife.utils.ResolveData;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.view.LineChartView;

import static com.jstyle.blesdk.cmdenum.SendCmdState.Set_EXERCISE_MODE;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link Heart1810Fragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class Heart1810Fragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_ecghistory_date)
    Button btEcghistoryDate;
    @BindView(R.id.iv_date)
    ImageView ivDate;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.CalendarView_sleep_Month)
    CalendarView CalendarViewSleepMonth;
    @BindView(R.id.tv_health_heart)
    TextView tvHealthHeart;
    @BindView(R.id.tv_health_hr)
    TextView tvHealthHr;
    @BindView(R.id.LineChartView_health_heart)
    LineChartView LineChartViewHealthHeart;
    @BindView(R.id.ScrollView)
    NestedScrollView ScrollView;
    @BindView(R.id.CalendarLayout)
    com.haibin.calendarview.CalendarLayout CalendarLayout;
    Unbinder unbinder;
    @BindView(R.id.iv_heart_measure_bg)
    ImageView ivHeartMeasureBg;
    @BindView(R.id.tv_heart_measure_time)
    TextView tvHeartMeasureTime;
    @BindView(R.id.tv_heart_measure_start)
    TextView tvHeartMeasureStart;
    @BindView(R.id.iv_heart_measure_line)
    ImageView ivHeartMeasureLine;
    @BindView(R.id.iv_heart_measure)
    ImageView ivHeartMeasure;
    @BindView(R.id.tv_bpm)
    TextView tvBpm;
    @BindView(R.id.tv_hr1810_value)
    TextView tvHr1810Value;
    @BindView(R.id.tv_hr_level)
    TextView tvHrLevel;
    @BindArray(R.array.hr_color1810_arrays)
    int[]hrColorArrays;
    private Typeface mFace;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    String findDate;
    private OnFragmentInteractionListener mListener;
    private AnimationDrawable animationDrawable;
    private AnimationDrawable animationDrawableHeart;
    private Disposable disposable;
    @BindArray(R.array.heartRange_array)
    String[] heartArray;
    public Heart1810Fragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment Heart1810Fragment.
     */
    // TODO: Rename and change types and number of parameters
    public static Heart1810Fragment newInstance(String param1, String param2) {
        Heart1810Fragment fragment = new Heart1810Fragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_heart1810, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        mFace = Typeface.createFromAsset(getActivity().getAssets(), "Brandon_reg.otf");

//
//        findData(nowDate);
        CalendarViewSleepMonth.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {
                String date = calendar.getYear() + "." + String.format("%02d", calendar.getMonth()) + "." + String.format("%02d", calendar.getDay());
                btEcghistoryDate.setText(date);
                findData(date);
            }
        });
    }

    private void findData(String date) {
        findDate = date;
        initHeartView(date);
    }

    private void initHeartView(String queryDate) {
        List<HeartData> heartDataList = HeartDataDaoManager.queryDayData(queryDate.substring(2));
        int maxDayHr = 0;
        int minDayHr = 300;
        int totalDayHr = 0;
        int count = 0;

        int offsetCount = 5;
        int firstCount = -1;
        HashMap<Integer, Integer> offsetMap = new HashMap<>();
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00", 1);
            int heartRate = heartData.getHeart();
            // if (startCount >= 1440) break;
            if (heartRate != 0) {
                if (firstCount != -1) {
                    offsetCount = startCount - firstCount;
                    Integer offset = offsetMap.get(offsetCount);
                    if (offset == null) {
                        offsetMap.put(offsetCount, 1);
                    } else {
                        offset++;
                        offsetMap.put(offsetCount, offset);
                    }
                }
                firstCount = startCount;
                count++;
                totalDayHr += heartRate;
                maxDayHr = Math.max(maxDayHr, heartRate);
                minDayHr = Math.min(minDayHr, heartRate);
            }

        }
        int maxOffset = 0;
        int drawOffset = 5;
        for (Map.Entry<Integer, Integer> entry : offsetMap.entrySet()) {
            if (entry.getValue() > maxOffset) {
                maxOffset = entry.getValue();
                drawOffset = entry.getKey();
            }
        }
//        if (drawOffset < 5) drawOffset = 5;
//        if (drawOffset > 60) drawOffset = 60;
        int[] heartArray = new int[1440 ];//24*60分钟
        for (int i = 0; i < heartDataList.size(); i++) {
            HeartData heartData = heartDataList.get(i);
            String date = heartData.getTime();
            int startCount = DateUtil.getMIndex(date, queryDate.split(" ")[0] + " 00:00:00", 1);
            int heartRate = heartData.getHeart();
            if (startCount >= 1440 ) break;
            if (heartRate != 0) {
                heartArray[startCount] = heartRate;
            }
        }

        float top = 0;
        if (maxDayHr % 10 == 0) {
            top = maxDayHr;
        } else {
            top = (((int) maxDayHr / 10) + 1) * 10;
        }

        ChartDataUtil.initDataChartView(LineChartViewHealthHeart, -0.5f, top + 10, heartArray.length, 30);
        LineChartViewHealthHeart.setLineChartData(ChartDataUtil.getHistoryHeartDayChart(getActivity(), heartArray, mFace, 0, top));
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        unSubscribe(disposable);
    }

    @OnClick(R.id.ll_date)
    public void onViewClicked() {
        if (CalendarLayout.isExpand()) {
            CalendarLayout.shrink();
            ivDate.setRotation(0);
        } else {
            ivDate.setRotation(180);
            ScrollView.fling(0);
            ScrollView.smoothScrollTo(0, 0);
            CalendarLayout.expand();
        }
    }

    @OnClick({R.id.tv_health_heart, R.id.tv_health_hr, R.id.tv_heart_measure_start})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_heart_measure_start:
                if (BleManager.getInstance().isConnected()) {
                    startMeasure = !startMeasure;
                    startMeasureHeart(startMeasure);
                    ExerciseMode exerciseMode = new ExerciseMode();
                    exerciseMode.setEnableStatus(startMeasure ? ExerciseMode.Status_START : ExerciseMode.Status_FINISH);
                    sendData(Set_EXERCISE_MODE, exerciseMode);
                }

                break;
            case R.id.tv_health_heart:
                startActivity(HeartHistoryActivity.class, HealthHistoryActivity.KEY_DATA_DATE, findDate.substring(2));


                break;
            case R.id.tv_health_hr:
                startTipsActivity(HeartTipsActivity.TipsType_Heart);
                break;
        }
    }

    boolean startMeasure;

    private void startMeasureHeart(boolean startMeasure) {
        tvHeartMeasureStart.setText(startMeasure ? getString(R.string.stop) : getString(R.string.start));
        ivHeartMeasureBg.setImageResource(startMeasure ? R.drawable.bg_heart_circle_stop : R.drawable.bg_heart_circle_start);
        if (startMeasure) {
            startTimer();
            if (animationDrawable != null && animationDrawable.isRunning()) return;
            animationDrawable = (AnimationDrawable) ivHeartMeasureLine.getDrawable();
            animationDrawable.start();
            animationDrawableHeart = (AnimationDrawable) ivHeartMeasure.getDrawable();
            animationDrawableHeart.start();
        } else {
            unSubscribe(disposable);
            if (animationDrawable != null) animationDrawable.stop();
            if (animationDrawableHeart != null) animationDrawableHeart.stop();
            tvHr1810Value.setText("--");
            tvHrLevel.setText("--");
            tvHeartMeasureTime.setText("0s");
        }

    }
    public void onDisconnect(){
        startMeasureHeart(false);
    }

    private void startTimer() {
        if (disposable != null && !disposable.isDisposed()) return;
        Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(Long aLong) {
                tvHeartMeasureTime.setText(String.valueOf(aLong) + "s");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    public void updateHeartData(Map<String, String> maps) {
        if (isAdded()) {
            String heart = maps.get(DeviceKey.KHeartValue);
            if (Integer.valueOf(heart) != 0) {
                String account = NetWorkUtil.getUserId();
                UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
                if (userInfo == null) {
                    userInfo = new UserInfo();
                    userInfo.setUserId(account);
                    UserInfoDaoManager.insertUser(userInfo);
                }
                String birthday = userInfo.getBirthday();
                int userYear = Integer.parseInt(birthday.split("-")[0]);
                java.util.Calendar calendar = java.util.Calendar.getInstance();
                int age = calendar.get(java.util.Calendar.YEAR) - userYear;
                int MHR = 220 - age;
                int level = ResolveData.getHeartRange(Integer.valueOf(heart), MHR);
                if(level!=-1){
                    tvHrLevel.setText(heartArray[level]);
                    tvHrLevel.setTextColor(hrColorArrays[level]);
                }

                tvHr1810Value.setText(heart);
                startMeasure = true;
                startMeasureHeart(startMeasure);
            }

        }


    }

    private void startTipsActivity(int type) {
        Intent intent = new Intent(getActivity(), HeartTipsActivity.class);
        intent.putExtra(HeartTipsActivity.TipsType, type);
        startActivity(intent);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
